# Methods added to this helper will be available to all templates in the application.

module ApplicationHelper

  include FilterEngine

  def adv_select_tag(name, options, selected, html_opts = { })
    options_tags = []
    puts "selected list for #{name}: #{selected}"
    options.each do |option|
      selected_html = ""
      if selected.count(option[1])>0
        selected_html = " selected='selected'"
      end
      options_tags<<"<option value='#{option[1]}'#{selected_html}>#{option[0]}</option>"
    end
    select_tag name, options_tags.join(' '), html_opts
  end

  def columns_names_select(query)
    to_show = []
    cols = columns_for(query)
    cols.each do |col|
      if query.foreign_keys[col.name].nil?
        to_show<<[col.name,col.name]
      else
        to_show<<[query.foreign_keys[col.name][:alias], query.foreign_keys[col.name][:alias]]
      end
    end
    adv_select_tag "#{query.table_name}_columns", to_show.map, []
  end

  def operations_select(criteria)
    adv_select_tag "#{criteria.name}_operation", operations_for(criteria).collect{ |o| [o, o]}, [criteria.operator]
  end

  def criteria_value(criteria)
    if criteria.foreign?
      adv_select_tag "#{criteria.name}_value", criteria.foreign_collection , criteria.values_list, :multiple => true
    else
      text_field_tag "#{criteria.name}_value", criteria.value
    end
  end

end
